import React, { useEffect, useState } from 'react'
import { Button, Space, Table, message, Popconfirm } from 'antd';
import '../components.css'
import RolesService from '../../services/RolesService'
import { Link } from 'react-router-dom';
import { DeleteOutlined, UpCircleOutlined } from '@ant-design/icons';

export default function RoleList() {

  const [roles, setroles] = useState([])

  const getAllRoles = () => {
    RolesService.getAllRoles().then((response) => {
      setroles(response.data);
    }).catch(error => {
      console.log(error);
    })
  }

  useEffect(() => {
    getAllRoles();
  }, [])


  const deleteRole = (r) => {
    console.log(r);
    message.success('Delete success!');
    setTimeout(() => {
      RolesService.deleteRole(r).then(response => {
        getAllRoles();
      }).catch(error => {

      })
    }, 500);
  }

  const cancel = (r) => {
    console.log(r);
    message.error('Delete Failed!');
  };


  const columns = [
    {
      title: 'Role Id',
      dataIndex: 'roleId',
      key: 'roleId',
      align: 'center',

    },
    {
      title: 'Role Age',
      dataIndex: 'roleAge',
      key: 'roleAge',
      align: 'center',

    },

    {
      title: 'Role Gender',
      dataIndex: 'roleGender',
      key: 'roleGender',
      align: 'center',

    },
    {
      title: 'Role Job',
      dataIndex: 'roleJob',
      key: 'roleJob',
      align: 'center',

    },
    
    
    {
      title: 'Role Name',
      dataIndex: 'roleName',
      key: 'roleName',
      align: 'center',
    },

    {
      title: 'Role Address',
      dataIndex: 'roleAddress',
      key: 'roleAddress',
      align: 'center',
    },

  
    {
      title: 'Actions',
      key: 'actions',
      align: 'center',
      render: (_, record) => (
        <Space size="middle">
          <Button type='primary' icon={<UpCircleOutlined />}>
            <Link to={"updaterole/" + record.key}
              style={{ color: "white", paddingLeft: "9px" }}>Update</Link>
          </Button>
          <Popconfirm
            title="Are you sure to delete?"
            onConfirm={() => deleteRole(record.key)}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <Button type='danger' icon={<DeleteOutlined />}>Delete</Button>
          </Popconfirm>
        </Space>
      )
    }

  ];
  const data = roles.map((role) => {
    console.log(role)
    return {
      key: role.id,
      roleId: role.id,
      roleJob: role.roleJob,
      roleGender:role.roleGender,
      roleAge: role.roleAge,
      roleAddress: role.roleAddress,
      roleName:role.roleName,
    }
  })

  return (
    <div> className='emplst'
      <div className="title">List Roles</div>
      <Table columns={columns} dataSource={data} bordered={true} />

    </div>
  )
}
